package com.panda.web.service.rests.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.panda.web.controller.rests.ProAddrs;
import com.panda.web.domain.dto.rests.AnnouncementDTO;
import com.panda.web.domain.vo.rests.AnnouncementVO;
import com.panda.web.entity.rests.Announcement;
import com.panda.web.mapper.rests.AnnouncementMapper;
import com.panda.web.mapper.rests.ProAddrsMapper;
import com.panda.web.service.rests.IAnnouncementService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Year;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.Objects;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;
import com.panda.web.utils.pageutils.PageResult;
import org.springframework.transaction.annotation.Transactional;


/**
 * 公告
 * Service业务层处理
 *
 * @author cpanda
 * @date 2025-09-08
 */
@Slf4j
@Service
public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Announcement> implements IAnnouncementService {
    @Autowired
    AnnouncementMapper announcementMapper;
    @Autowired
    ProAddrsMapper proAddrsMapper;

    /**
     * 分页查询
     *
     * @param dto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<AnnouncementVO> PageList(AnnouncementDTO dto, Integer pageNum, Integer pageSize) {

        Page<Announcement> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Announcement> queryWrapper = new QueryWrapper();//需要处理查询条件
        if (dto.getTypeAnn() != null) {
            if (Objects.equals(dto.getTypeAnn(), "1")) {
                if (dto.getQuanbu() != null) {
                    queryWrapper.like("name", dto.getQuanbu());
                }

            } else if (Objects.equals(dto.getTypeAnn(), "2")) {
                if (dto.getQuanbu() != null) {
                    queryWrapper.like("company_name", dto.getQuanbu());
                }

            } else if (Objects.equals(dto.getTypeAnn(), "3")) {
                if (dto.getQuanbu() != null) {
                    queryWrapper.like("content", dto.getQuanbu());
                }

            }
        }
//        if (dto.getQuanbu()!=null){
//            queryWrapper.like("company_name",dto.getQuanbu()).or().like("name",dto.getQuanbu()).or().like("content",dto.getQuanbu());
//        }
        // 地址查询
        if (dto.getSsdizhi() != null && !dto.getSsdizhi().isEmpty()) {
            System.out.println(dto.getSsdizhi() + "   aaa");
            List<String> stringList = splitToList(dto.getSsdizhi());
            List<String> newAddress = removeCitySuffix(stringList);
            if (newAddress.contains("其他")) {
                newAddress.add("");
                newAddress.add("无");
            }
            System.out.println(newAddress);
            queryWrapper.and(wrapper -> {
                for (String address : newAddress) {
                    wrapper.or().like("address", address);
                }
            });

        }
        // 岗位类型
        if (dto.getSsgwlx() != null && !dto.getSsgwlx().trim().isEmpty()) {
            List<String> gangweiList = splitToList(dto.getSsgwlx());
            queryWrapper.and(wrapper -> {
                for (String gangwei : gangweiList) {
                    wrapper.or().like("content", gangwei);
                }
            });
        }
        //学历
        if (dto.getSsxllx() != null && !dto.getSsxllx().trim().isEmpty()) {
            List<String> stringList = getBacjground(dto.getSsxllx());
            queryWrapper.and(wrapper -> {
                for (String xueli : stringList) {
                    wrapper.or().like("content", xueli);
                }
            });
        }
//        if (dto.getSszhuanye() != null) {
//            List<String> majorcnList = splitToList(dto.getSszhuanye());
//            List<String> processedMajors;
//            if (dto.getSsxllx() != null && !dto.getSsxllx().trim().isEmpty()) {
//
//                if (Objects.equals(dto.getEducationcn(), "本科") || Objects.equals(dto.getEducationcn(), "大专")) {
//                    // 本科和大专：检查数组中是否包含一级学科
//                    boolean containsUndergraduate = dto.getMajorcnList().stream()
//                            .anyMatch(major -> major != null && containsUndergraduateDiscipline(major));
//
//                    if (containsUndergraduate) {
//                        // 包含一级学科，直接返回去重数组，处理"-"和去掉"类"字
//                        processedMajors = dto.getMajorcnList().stream()
//                                .filter(major -> major != null && !major.trim().isEmpty() && !"-".equals(major.trim()))
//                                .map(major -> removeClassSuffix(major.trim()))
//                                .distinct()
//                                .collect(Collectors.toList());
//                    } else {
//                        // 不包含一级学科，去掉第一个（一级学科），只保留后面的
//                        processedMajors = dto.getMajorcnList().stream()
//                                .filter(major -> major != null && !major.trim().isEmpty() && !"-".equals(major.trim()))
//                                .skip(1) // 跳过第一个
//                                .map(major -> removeClassSuffix(major.trim()))
//                                .distinct()
//                                .collect(Collectors.toList());
//                    }
//                } else {
//                    // 硕士：检查数组中是否包含一级学科
//                    boolean containsGraduate = dto.getMajorcnList().stream()
//                            .anyMatch(major -> major != null && containsGraduateDiscipline(major));
//
//                    if (containsGraduate) {
//                        // 包含一级学科，直接返回去重数组，处理"-"和去掉"类"字
//                        processedMajors = dto.getMajorcnList().stream()
//                                .filter(major -> major != null && !major.trim().isEmpty() && !"-".equals(major.trim()))
//                                .map(major -> removeClassSuffix(major.trim()))
//                                .distinct()
//                                .collect(Collectors.toList());
//                    } else {
//                        // 不包含一级学科，去掉第一个（一级学科），只保留后面的
//                        processedMajors = dto.getMajorcnList().stream()
//                                .filter(major -> major != null && !major.trim().isEmpty() && !"-".equals(major.trim()))
//                                .skip(1)
//                                .map(major -> removeClassSuffix(major.trim()))
//                                .distinct()
//                                .collect(Collectors.toList());
//
//                    }
//                }
//
//                // 使用处理后的专业列表进行查询
//                if (!processedMajors.isEmpty()) {
//                    System.out.println(processedMajors + "  1  111 1");
//                    List<String> finalProcessedMajors = processedMajors;
//                    dto.setMajList(finalProcessedMajors);
//                }
//            }
//        }

// 获取当前年份的第一天和最后一天
        int currentYear = Year.now().getValue();
        LocalDateTime startOfYear = LocalDateTime.of(currentYear, 1, 1, 0, 0, 0);
        LocalDateTime endOfYear = LocalDateTime.of(currentYear, 12, 31, 23, 59, 59);
        queryWrapper.between("publish_time", startOfYear, endOfYear)  // 查询今年范围内的数据
                .orderByDesc("publish_time");  // 按发布时间倒序排列
        IPage<Announcement> announcementIPage = announcementMapper.selectPage(page, queryWrapper);
        long total = announcementIPage.getTotal();
        List<Announcement> records = announcementIPage.getRecords();
        List<AnnouncementVO> voList = announcementVoToList(records);//封装vo数据方法
        return new PageResult<>(voList, total, pageNum, pageSize);
    }

    public String convertToDateTime(String date, boolean isEndTime) {
        LocalDateTime localDateTime = LocalDate.parse(date).atStartOfDay(); // 默认将日期转为 00:00:00
        if (isEndTime) {//true 返回结束时间
            localDateTime = localDateTime.withHour(23).withMinute(59).withSecond(59); // 如果是结束时间，设置为 23:59:59
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return localDateTime.format(formatter);  // 格式化为所需的字符串
    }

    /**
     * 无分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public List<AnnouncementVO> choiceList(AnnouncementDTO dto) {
        QueryWrapper<Announcement> queryWrapper = new QueryWrapper();//需要处理查询条件
        //构建查询条件
        List<Announcement> announcementList = announcementMapper.selectList(queryWrapper);
        List<AnnouncementVO> voList = announcementVoToList(announcementList);//封装vo数据方法
        return voList;
    }

    /**
     * 回显数据
     *
     * @param announcementId
     * @return
     */
    @Override
    public AnnouncementVO selectById(Long announcementId) {
        AnnouncementVO vo = new AnnouncementVO();
        Announcement announcement = announcementMapper.selectById(announcementId);
        BeanUtils.copyProperties(announcement, vo);
        return vo;
    }

    /**
     * 删除数据(逻辑删除)
     *
     * @param ids
     * @return
     */
    @Override
    public int removeByAnnouncementIds(List<Long> ids) {
        for (Long id : ids) {
            announcementMapper.deleteById(id);
        }
        return 1;
    }

    /**
     * @param addrs
     * @return
     */
    @Override
    public List<ProAddrs> getAddre(ProAddrs addrs) {
        QueryWrapper<ProAddrs> queryWrapper = new QueryWrapper<>();
        if (addrs.getName() != null) {
            queryWrapper.like("name", addrs.getName());
        }
        List<ProAddrs> addrsList = proAddrsMapper.selectList(queryWrapper);
        return addrsList;
    }


    // 处理VO数据封装
    private List<AnnouncementVO> announcementVoToList(List<Announcement> announcementList) {
        List<AnnouncementVO> voList = new ArrayList<>();
        if (announcementList.size() > 0 && !announcementList.isEmpty()) {
            for (Announcement announcement : announcementList) {
                AnnouncementVO vo = new AnnouncementVO();
                BeanUtils.copyProperties(announcement, vo);
                voList.add(vo);
            }
        }
        return voList;
    }

    public static List<String> splitToList(String str) {
        if (str == null || str.trim().isEmpty()) {
            return new ArrayList<>();
        }
        // 支持逗号、中文逗号分隔
        return Arrays.stream(str.split("[,，]"))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .collect(Collectors.toList());
    }

    public static List<String> removeCitySuffix(List<String> areaChList) {
        // 创建一个新的列表，用来存储去除"市"后的城市名称
        List<String> resultList = new ArrayList<>();

        // 遍历原始列表，去除每个城市名称中的"市"
        for (String area : areaChList) {
            // 去除 "市" 字符串
            String cityWithoutSuffix = area.replace("市", "");
            // 将处理后的城市名称添加到新的列表
            resultList.add(cityWithoutSuffix);
        }


        return resultList;
    }
    private List<String> getBacjground(String background) {

        List<String> backgroundList = new ArrayList<>();  //学历
        if (Objects.equals(background, "大专")) {
            backgroundList.add("大专");
            backgroundList.add("专科及以上");
        } else if (Objects.equals(background, "硕士")) {
            backgroundList.add("硕士");
            backgroundList.add("硕士及以上");
            backgroundList.add("本科");
            backgroundList.add("本科及以上");
        } else if (Objects.equals(background, "博士")) {
            backgroundList.add("博士");
            backgroundList.add("硕士");
            backgroundList.add("硕士及以上");
            backgroundList.add("博士及以上");
        } else if (Objects.equals(background, "本科")) {
            backgroundList.add("本科");
            backgroundList.add("本科及以上");
            backgroundList.add("大专");
            backgroundList.add("专科及以上");
        } else {
            backgroundList.add("大专");
            backgroundList.add("中专");
            backgroundList.add("中技");
            backgroundList.add("初中");
            backgroundList.add("高中");
            backgroundList.add("初中及以下");
        }
        return backgroundList;
    }
}